package com.xinghanlaser.applet.base.flow.core;

import cn.hutool.core.bean.BeanUtil;
import com.xinghanlaser.applet.base.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/11 10:07
 */
@Slf4j
public abstract class BasePoint<T> {
    public void run(Map<String ,Object> pointData, Validator validator){
        try {
            // 数据转换
            Class<T> dataType = getPointDataType();
            T data = BeanUtil.toBean(pointData, dataType);

            // 参数校验
            validatedData(data, validator);

            // 节点操作
            pointOperation(data);

        }catch (ServiceException | ConstraintViolationException e){
            throw e;
        }
        catch (Exception e){
            log.error(e.getMessage());
            throw new ServiceException("流程执行错误");
        }

    }
    protected abstract void pointOperation(T pointData);

    protected abstract Class<T> getPointDataType();

    public abstract Long getPointId();

    private void validatedData(T pointData, Validator validator){
        Set<ConstraintViolation<T>> violations = validator.validate(pointData);
        if(!violations.isEmpty()){
            throw new ConstraintViolationException(violations);
        }
    }



}
